<?php
/**
 * 拉卡拉对账服务
 * @author angl
 */

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/common/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

//获取到明天间隔
function get_time_diff()
{
    $time1 = $date1 = date("Y-m-d H:i:s");
    $time2 = date("Y-m-d 00:30:00", strtotime("+ 1 day"));
    $s = strtotime($time2) - time();
    logUtil("currtime:$time1, nexttime:$time2,timediff:$s");
    return $s;
}


while (true) {
    //计算昨日时间
    $yesterday = date("Y-m-d",strtotime('-1 day'));
    try {
        $db = init_db();
        $bill_list = $db->where('deal_time', [$yesterday . " 00:00:00", $yesterday . " 23:59:59"], 'BETWEEN')
            ->where('pay_result',1)
            ->where('third_party',1)
            ->get("recharge_log");
        if(empty($bill_list)){
            logUtil("No bills yesterday");
            $s = get_time_diff();
            sleep($s);
            continue;
        }
        $db->insert('lakala_bill',['create_date'=>$yesterday]);
        foreach ($bill_list as $bill){
            $remark = json_decode($bill['remark'],true);
            $db->where('create_date',$yesterday)->update('lakala_bill',[
                'settlement_money'=> $db->inc($bill['amount']),
                'amount'=>$db->inc(1),
                'poundage'=>$db->inc($remark['data']['orderFee'])
            ]);
            logUtil("车商: {$bill['dealer_id']} 于{$bill['deal_time']} 充值 {$bill['amount']} ");
        }
        logUtil("Today task finished");
        $s = get_time_diff();
        sleep($s);
        continue;
    } catch (Exception $e) {
        logUtil($e->getCode() . ": " . $e->getMessage(), "ERROR");
        sleep(60);
    }
}
